<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!-- <script src="http://img.mukewang.com/down/540812440001e40e00000000.js" type="text/javascript"></script> -->
   <script src="core.js"></script>
   <script src="sizzle.js"></script>
   <script src="other.js"></script>
<title></title>
</head>
<body>

<script type="text/javascript">

function fn1() {
  var defer = $.Deferred();
  setTimeout(function(){
    defer.resolve('fn1');
  },500)
  return defer;
}

function fn2(){
  var defer = $.Deferred();
  setTimeout(function(){
    defer.resolve('fn2');
  },1000)
  return defer;
}

// $.when(fn1(), fn2()).then(function() {
//   console.log('成功',arguments)
// },function(){
//   console.log('失败',arguments)
// })


function when() {

    var resolveContexts, resolveValues,
      resolveValues = [].slice.call(arguments),
      remaining = resolveValues.length;

    //内部deferred对象
    var deferred = $.Deferred();

    function collector(i, contexts, values) {
      return function(value) {
        contexts[i] = this;
        values[i] = arguments.length > 1 ? [].slice.call(arguments)(arguments) : value;
        if (remaining === 1) {
          deferred.resolveWith(contexts, values);
        } else {
          --remaining;
        }
      };
    };

    var resolveContexts,resolveValues;
    for (var i = 0; i < remaining; i++) {
        progressValues = new Array( resolveValues.length );
        resolveContexts = new Array( resolveValues.length );
        resolveValues[i].promise()
          .done(collector(i, resolveContexts, resolveValues))
          .fail(deferred.reject)
    }

    return deferred;
}


when(fn1(), fn2()).done(function() {
  console.log(arguments)
})

</script>

</body>
</html>















